﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Suzsoft.Smart.Data;
using ESOL.Common.Entity;


namespace ESOL.Business.ProcessingService
{
    public class SalesToPlan
    {
        private static ProdPlanOrderEntity CreatePlanOrder(SalesProdPlanApplicationEntity salesApplication, SalesProdPlanApplicationItemEntity salesApplicationItem)
        {
            ProdPlanOrderEntity planOrder = new ProdPlanOrderEntity();
            planOrder.PlanOrderId = Guid.NewGuid().ToString();
            planOrder.ApplicationItemId = salesApplicationItem.ApplicationItemId;
            BptBlueprintEntity blueprint = ESOL.Business.Bpt.BptBlueprintBs.GetBptBlueprintByProductID(salesApplicationItem.ProductId);
            if (blueprint != null)
            {
                planOrder.BlueprintId = blueprint.BlueprintId;
            }
            planOrder.Qty = salesApplicationItem.Qty;
            if (salesApplicationItem.RequiredDeliveryDate != null)
            {
                if (!salesApplicationItem.RequiredDeliveryDate.ToString("yyyy-MM-dd").Equals("1900-01-01")
                    && !salesApplicationItem.RequiredDeliveryDate.ToString("yyyy-MM-dd").Equals("0001-01-01"))
                {
                    planOrder.DeliveryDate = salesApplicationItem.RequiredDeliveryDate;
                }
            }
            else if (salesApplication.DeliveryDate != null)
            {
                if (!salesApplication.DeliveryDate.ToString("yyyy-MM-dd").Equals("1900-01-01")
                    && !salesApplication.DeliveryDate.ToString("yyyy-MM-dd").Equals("0001-01-01"))
                {
                    planOrder.DeliveryDate = salesApplication.DeliveryDate;
                }
            }
            planOrder.PlanOrderPersn = Common.CommonParameter.CurrentUser.PersonId;
            planOrder.PlanOrderDate = DateTime.Today;
            planOrder.CreatedDate = DateTime.Today;
            planOrder.CreatedBy = Common.CommonParameter.CurrentUser.PersonId;
            planOrder.LastModifiedDate = DateTime.Today;
            planOrder.LastModifiedBy = Common.CommonParameter.CurrentUser.PersonId;
            planOrder.Status = "PSTATUS01";
            return planOrder;
        }

        private static BptApplicationEntity CreateBptApplication(SalesProdPlanApplicationEntity salesApplication)
        {
            BptApplicationEntity bptApp = new BptApplicationEntity();
            bptApp.ApplicationId = Guid.NewGuid().ToString();
            bptApp.ProdApplicationId = salesApplication.ApplicationId;
            bptApp.ApplicationPerson = salesApplication.ApplicationPerson;
            bptApp.Remark = "审核生产计划申请单时自动生成";
            bptApp.CreatedDate = DateTime.Now;
            bptApp.CreatedBy = salesApplication.ApprovedBy;
            bptApp.LastModifiedDate = DateTime.Now;
            bptApp.LastModifiedBy = salesApplication.ApprovedBy;
            bptApp.Status = "DRAW01";
            bptApp.ApplicationType = "DT01";
            return bptApp;
        }

        private static BptApplicationItemEntity CreateBptApplicationItem(BptApplicationEntity bptApp,SalesProdPlanApplicationItemEntity item)
        {
            BptApplicationItemEntity bptItem = new BptApplicationItemEntity();
            bptItem.ApplicationItemId = Guid.NewGuid().ToString();
            bptItem.ApplicationId = bptApp.ApplicationId;
            bptItem.PlanApplicationItemId = item.ApplicationItemId;
            bptItem.DeliveryDate = item.RequiredDeliveryDate;
            bptItem.Remark = "审核生产计划申请单时自动生成";
            bptItem.ProductSpecIn = item.ProductSpecIn;
            bptItem.ProductSpecOut = item.ProductSpecOut;
            bptItem.Material = item.Material;
            bptItem.DiameterOut = item.DiameterOut;
            bptItem.DiameterIn = item.DiameterIn;
            bptItem.Length = item.Length;
            bptItem.Unit = item.Unit;
            return bptItem;
        }

        private static FinCustomerAccountItemEntity CreateFinAccountItem(SalesProdPlanApplicationEntity salesApplication)
        {
            FinCustomerAccountItemEntity accountItem = new FinCustomerAccountItemEntity();
            accountItem.CustomerAccountItemId = Guid.NewGuid().ToString();
            accountItem.CustomerId = salesApplication.CustomerId;
            accountItem.AmountPerson = salesApplication.ApplicationPerson;
            accountItem.AmountDate = salesApplication.ApplicationDate;
            accountItem.SalesOrderAmount = salesApplication.TotalAmount;
            accountItem.RelatedOrderId = salesApplication.ApplicationId;
            accountItem.RelatedOrderCode = "生产计划单:" + salesApplication.ApplicationCode;
            accountItem.ApplicationId = salesApplication.ApplicationId;
            return accountItem;
        }

        public static bool ApproveSalesApplication(SalesProdPlanApplicationEntity salesApplication, out string msg)
        {
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                msg = null;
                try
                {
                    broker.BeginTransaction();
                    //审核生产计划申请单
                    if (salesApplication.Status.Equals("STATUS03") || salesApplication.Status.Equals("STATUS04"))
                    {
                        msg = "单据已审核!";
                        return false;
                    }
                    salesApplication.Status = "STATUS03";
                    //分析申请单明细：无编码或BOM的，生成制图申请；有编码和BOM的，生成计划单；
                    List<SalesProdPlanApplicationItemEntity> salesApplicationItems = new List<SalesProdPlanApplicationItemEntity>();
                    salesApplicationItems = ESOL.Business.Sales.SalesProdPlanApplicationItemBs.GetProdPlanApplicationItemByAppID(salesApplication.ApplicationId);
                    List<BptApplicationEntity> bptApplications = new List<BptApplicationEntity>();
                    List<BptApplicationItemEntity> bptApplicationItems = new List<BptApplicationItemEntity>();
                    List<ProdPlanOrderEntity> planOrders = new List<ProdPlanOrderEntity>();
                    FinCustomerAccountEntity finAccount = new FinCustomerAccountEntity();
                    FinCustomerAccountItemEntity finItem = new FinCustomerAccountItemEntity();
                    foreach (SalesProdPlanApplicationItemEntity applicationItem in salesApplicationItems)
                    {
                        BptBlueprintEntity mBlueprint = ESOL.Business.Bpt.BptBlueprintBs.GetBptBlueprintByProductID(applicationItem.ProductId);
                        if (string.IsNullOrEmpty(applicationItem.ProductId) || mBlueprint == null)
                        {
                            BptApplicationEntity bptApp = CreateBptApplication(salesApplication);
                            bptApplications.Add(bptApp);
                            BptApplicationItemEntity bptItem = CreateBptApplicationItem(bptApp,applicationItem);
                            bptApplicationItems.Add(bptItem);
                        }
                        else
                        {
                            ProdPlanOrderEntity planOrder = CreatePlanOrder(salesApplication, applicationItem);
                            planOrders.Add(planOrder);
                        }
                    }
                    Sales.SalesProdPlanApplicationBs.UpdateSalesProdPlanApplication(salesApplication, broker);
                    finItem = CreateFinAccountItem(salesApplication);
                    finAccount = FinCommonFunctions.GetByCustomerId(salesApplication.CustomerId);
                    if (ESOL.Business.Bpt.BptApplicationBs.CreateBptApplications(bptApplications,broker) == false)
                    {
                        broker.RollBack();
                        return false;
                    }
                    DataAccess.Insert<BptApplicationItemEntity>(bptApplicationItems, broker);
                    if (ESOL.Business.Prod.ProdPlanOrderBs.CreateProdPlanOrders(planOrders, broker) == false)
                    {
                        broker.RollBack();
                        return false;
                    }
                    DataAccess.Insert(finItem,broker);
                    finAccount.SalesOrderAmount += finItem.SalesOrderAmount;
                    broker.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    broker.RollBack();
                    throw ex;
                }
            }
        }
    }
}
